package com.corpgovernment.organization.service.impl;

import com.corpgovernment.api.basic.dto.OrgDTO;
import com.corpgovernment.api.basic.enums.SourceEnum;
import com.corpgovernment.api.basic.metadata.ELoginStatus;
import com.corpgovernment.api.basic.vo.UserLoginResponseVo;
import com.corpgovernment.api.organization.enums.LoginTypeEnum;
import com.corpgovernment.common.base.BaseUserInfo;
import com.corpgovernment.common.base.CommonException;
import com.corpgovernment.organization.entity.db.MbOrgInfo;
import com.corpgovernment.organization.service.IOrganizationInfoService;
import com.corpgovernment.organization.util.OrganizationUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author jhxue
 * @create 2022-02-18-14:21
 */
@Service
@Slf4j
public class AccountLoginSourceService extends AbstractLoginSourceService {

    @Autowired
    private IOrganizationInfoService organizationInfoService;


    public boolean checkDefaultOrg(List<OrgDTO> orgDTOList) {
        OrgDTO orgDTO = orgDTOList.get(0);
        MbOrgInfo byOrgId = organizationInfoService.findByOrgId(orgDTO.getDeptId());
        if (Objects.nonNull(byOrgId) && byOrgId.getId() < 0) {
            return true;
        }
        return false;
    }


    @Override
    public UserLoginResponseVo process(BaseUserInfo userInfo, UserLoginResponseVo response, LoginTypeEnum loginType) {
        // 前台用户查询身份
        Map<Integer, List<OrgDTO>> userOrgMap = OrganizationUtils.genUserOrgInfo(userInfo.getUid());
        response.setLogined(false);
        response.setNoOrgFlag(false);
        response.setSource(userInfo.getSource());

        // 如果此时是多身份并且已知用户的组织(ticket登录的情况，用户多身份会先选好组织id)，则将userOrgMap改为选好的身份
        if (loginType == LoginTypeEnum.TICKET && this.selectIdentity(userOrgMap) && StringUtils.isNotBlank(userInfo.getOrgId())) {
            List<OrgDTO> orgs = userOrgMap.remove(2);
            orgs = orgs.stream().filter(o -> StringUtils.equals(o.getDeptId(), userInfo.getOrgId(), false)).collect(Collectors.toList());
            userOrgMap.put(1, orgs);
        }
        if (this.oneIdentity(userOrgMap)) {
            boolean isDefault = checkDefaultOrg(userOrgMap.get(1));
            if (isDefault) {
                throw new CommonException(ELoginStatus.DEFAULT_ORG.getValue(), ELoginStatus.DEFAULT_ORG.getDesc());
            }
            // 有且仅有一个审核通过的身份直接登录成功标志
            this.loginSuccess(userOrgMap, userInfo, response);
            response.setLogined(true);
        } else if (this.selectIdentity(userOrgMap)) {
            boolean isDefault = checkDefaultOrg(userOrgMap.get(2));
            if (isDefault) {
                throw new CommonException(ELoginStatus.DEFAULT_ORG.getValue(), ELoginStatus.DEFAULT_ORG.getDesc());
            }
            // 选择身份后登陆
            this.setIdentity(userOrgMap, userInfo, response);
        } else if (this.noIdentity(userOrgMap)) {
            // 没有审核通过身份需要跳转到注册页面标识
            this.registerIdentity(userOrgMap, userInfo, response);
        }
        log.info("用户登录uid登录成功 accountName={},token={},是否是后台用户={},身份信息={}}", userInfo.getAccountName(), userInfo.getToken(), userInfo.getBgUser(), userOrgMap);
        return response;
    }

    @Override
    public SourceEnum[] getLoginSource() {
        return new SourceEnum[]{SourceEnum.PCBOOK, SourceEnum.APP};
    }
}
